<?php
namespace App;

use Model\Model;


class LoginController extends BaseController
{
    function post($request){
        $name = $this->valid('name',$request);
        $password = $this->valid('password',$request);
        if(!($name && $password))
            $this->response('参数错误');
        //执行mysql逻辑
        $model = new Model();
        //首先查看账户是否存在
        $st = $model->prepare("select * from `tbUsers` where `username`=?");
        $st->bindParam(1, $name);
        $st->execute();
        $res = $st->fetchAll();
        if($res == [])
            $this->response('没有该用户 请先注册');
        $res = $res[0];
        $currentDate = date('Y-m-d');
        if($res['error_count'] >5 && $res['last_login_time'] == $currentDate)
            $this->response('密码错误次数过过 请明天登录');
        //再查看密码是否正确
        $st = $model->prepare("select * from `tbUsers` where `username`=? and `password`=?");
        $st->bindParam(1, $name);
        $st->bindParam(2, $password);
        $st->execute();
        $userInfo = $st->fetchAll();
        if($userInfo == []) {
            //写入密码错误次数
            $lastLoginTime = $res['last_login_time'];
            if($lastLoginTime != $currentDate){
                //TODO 锁
                $st = $model->prepare("update `tbUsers` set `error_count`=1,`last_login_time`=? where `id`=?");
                $st->bindParam(1, $currentDate);
                $st->bindParam(2, $res['id']);
                $st->execute();
            }else{
                $st = $model->prepare("update `tbUsers` set `error_count`=`error_count`+1 where `id`=? ");
                $st->bindParam(1, $res['id']);
                $st->execute();
            }
            $this->response('密码错误');
        }
        //生成session过期的数据戳
        //生成session和session过期时间
        $session = uniqid();
        $uid = $res['id'];
        //生成过期时间
        $expireDate = loginExpireTime();
        $st = $model->prepare("insert into `tbSessions` (`session`,`uid`,`session_expire_time`) values (?,?,?)");
        $st->bindParam(1, $session);
        $st->bindParam(2, $uid);
        $st->bindParam(3, $expireDate);
        $res = $st->execute();
        if($res) {
            setcookie('session',$session);
            $this->redirect('http://10.0.1.10:8000/user/article');
        }else{
            $this->response('登录失败 系统错误');
        }


    }

    function get($request){
        $html = $this->display('login.html');
        $this->response($html);
    }

}